package com.qysoft.rapid.dao.mybatis;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import com.jfinal.plugin.activerecord.Page;
import com.qysoft.rapid.consts.RapidConsts;
import com.qysoft.rapid.exceptions.RapidException;
import com.qysoft.rapid.plugin.mybatis.MyBatisPlugin;
import com.qysoft.rapid.plugin.mybatis.MyBatisSessionManager;

/**
 * 封装mybatis数据库操作
 * @author liugong
 *
 */
public class MyBatisDao {
	
	/**
	 * 获取sqlsession
	 * @return
	 */
	private static SqlSession getSqlSession(){
		return MyBatisPlugin.getSqlSessionFactory().openSession(true);
	}
	

	/**
	 * 分页查询
	 * @param countSqlid
	 * @param dataSqlid
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public static Page<HashMap<String, Object>> paginateByXml(int page,int limit,String countSqlid,String dataSqlid,HashMap<String, Object> parameters) throws Exception{
		boolean isTx = false; //是否存在事务拦截
		SqlSession session = MyBatisSessionManager.getSession();
		if (session!=null) {
			isTx = true;
		}else {
			session = getSqlSession();
		}
		try {
			int start = (page-1)*limit;
			parameters.put("start", start); 
			int count = session.selectOne(countSqlid, parameters);
			List<HashMap<String, Object>> datas = session.selectList(dataSqlid, parameters);
			int totalPage = (int) (count / limit);
			if (count % limit != 0) {
				totalPage++;
			}
			return new Page<HashMap<String,Object>>(datas, page, limit, totalPage, count);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally{
			if (session!=null) {
				if (!isTx) {
					session.close();
				}
			}			
		}
	}
	
	/**
	 * selectOne
	 * @param sqlId
	 * @return
	 * @throws Exception
	 */
	public static <T> T selectOneByXml(String sqlId) throws Exception{
		boolean isTx = false; //是否存在事务拦截
		SqlSession session = MyBatisSessionManager.getSession();
		if (session!=null) {
			isTx = true;
		}else {
			session = getSqlSession();
		}
		try {
			return session.selectOne(sqlId);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if (session!=null) {
				if (!isTx) {
					session.close();
				}
			}
		}		
	}
	
	/**
	 * selectOne
	 * @param sqlId
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public static <T> T selectOneByXml(String sqlId,Object parameters) throws Exception{
		boolean isTx = false; //是否存在事务拦截
		SqlSession session = MyBatisSessionManager.getSession();
		if (session!=null) {
			isTx = true;
		}else {
			session = getSqlSession();
		}
		try {
			return session.selectOne(sqlId,parameters);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if (session!=null) {
				if (!isTx) {
					session.close();
				}
			}
		}		
	}
	
	/**
	 * selectList
	 * @param sqlId
	 * @return
	 * @throws Exception
	 */
	public static <T>List<T> selectListByXml(String sqlId) throws Exception{
		boolean isTx = false; //是否存在事务拦截
		SqlSession session = MyBatisSessionManager.getSession();
		if (session!=null) {
			isTx = true;
		}else {
			session = getSqlSession();
		}
		try {
			List<T> result = session.selectList(sqlId);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if (session!=null) {
				if (!isTx) {
					session.close();
				}
			}
		}		
	}
	
	/**
	 * selectList
	 * @param sqlId
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public static <T>List<T> selectListByXml(String sqlId,Object parameters) throws Exception{
		boolean isTx = false; //是否存在事务拦截
		SqlSession session = MyBatisSessionManager.getSession();
		if (session!=null) {
			isTx = true;
		}else {
			session = getSqlSession();
		}
		try {
			List<T> result = session.selectList(sqlId,parameters);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if (session!=null) {
				if (!isTx) {
					session.close();
				}
			}
		}		
	}	
	
	/**
	 * insert
	 * @param sqlId
	 * @throws Exception
	 */
	public static int insertByXml(String sqlId) throws Exception{
		boolean isTx = false; //是否存在事务拦截
		SqlSession session = MyBatisSessionManager.getSession();
		if (session!=null) {
			isTx = true;
		}else {
			session = getSqlSession();
		}
		try {
			int primaryKey = session.insert(sqlId);
			return primaryKey;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if (session!=null) {
				if (!isTx) {
					session.close();
				}
			}
		}
	}

	
	/**
	 * insert
	 * @param sqlId
	 * @param parameters
	 * @throws Exception
	 */
	public static int insertByXml(String sqlId,Object parameters) throws Exception{
		boolean isTx = false; //是否存在事务拦截
		SqlSession session = MyBatisSessionManager.getSession();
		if (session!=null) {
			isTx = true;
		}else {
			session = getSqlSession();
		}
		try {
			int primaryKey = session.insert(sqlId,parameters);
			if (!isTx) {
				session.commit();
			}
			return primaryKey;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if (session!=null) {
				if (!isTx) {
					session.close();
				}
			}
		}
	}
	
	/**
	 * delete
	 * @param sqlId
	 * @return
	 * @throws Exception
	 */
	public static int deleteByXml(String sqlId) throws Exception{
		boolean isTx = false; //是否存在事务拦截
		SqlSession session = MyBatisSessionManager.getSession();
		if (session!=null) {
			isTx = true;
		}else {
			session = getSqlSession();
		}
		try {
			int deleteCount = session.delete(sqlId);
			if (!isTx) {
				session.commit();
			}
			return deleteCount;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if (session!=null) {
				if (!isTx) {
					session.close();
				}
			}
		}
	}


	/**
	 * update
	 * @param sqlId
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public static int deleteByXml(String sqlId,Object parameters) throws Exception{
		boolean isTx = false; //是否存在事务拦截
		SqlSession session = MyBatisSessionManager.getSession();
		if (session!=null) {
			isTx = true;
		}else {
			session = getSqlSession();
		}
		try {
			int deleteCount = session.delete(sqlId,parameters);
			if (!isTx) {
				session.commit();
			}
			return deleteCount;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if (session!=null) {
				if (!isTx) {
					session.close();
				}
			}
		}
	}	
	
	/**
	 * update
	 * @param sqlId
	 * @return
	 * @throws Exception
	 */
	public static int updateByXml(String sqlId) throws Exception{
		boolean isTx = false; //是否存在事务拦截
		SqlSession session = MyBatisSessionManager.getSession();
		if (session!=null) {
			isTx = true;
		}else {
			session = getSqlSession();
		}
		try {
			int updateCount = session.update(sqlId);
			if (!isTx) {
				session.commit();
			}
			return updateCount;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if (session!=null) {
				if (!isTx) {
					session.close();
				}
			}
		}
	}


	/**
	 * update
	 * @param sqlId
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public static int updateByXml(String sqlId,Object parameters) throws Exception{
		boolean isTx = false; //是否存在事务拦截
		SqlSession session = MyBatisSessionManager.getSession();
		if (session!=null) {
			isTx = true;
		}else {
			session = getSqlSession();
		}
		try {
			int updateCount = session.update(sqlId,parameters);
			if (!isTx) {
				session.commit();
			}
			return updateCount;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if (session!=null) {
				if (!isTx) {
					session.close();
				}
			}
		}
	}
	
	/**
	 * 分页查询
	 * @param countSqlid
	 * @param dataSqlid
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public static Page<HashMap<String, Object>> paginateForExcelByXml(int page,int limit,String countSqlid,String dataSqlid,HashMap<String, Object> parameters) throws Exception{
		boolean isTx = false; //是否存在事务拦截
		SqlSession session = MyBatisSessionManager.getSession();
		if (session!=null) {
			isTx = true;
		}else {
			session = getSqlSession();
		}
		try {
			int start = (page-1)*limit;
			parameters.put("start", start);
			int count = session.selectOne(countSqlid, parameters);
			if (count>=RapidConsts.MAX_EXCEL_ROWS) {
				throw new RapidException("导出excel超出最大行数要求，每次导出应小于"+RapidConsts.MAX_EXCEL_ROWS+"行");
			}
			List<HashMap<String, Object>> datas = session.selectList(dataSqlid, parameters);
			List<HashMap<String, Object>> list = formatDatas(datas, dataSqlid);
			return new Page<HashMap<String,Object>>(list, page, limit, 0, count);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally{
			if (session!=null) {
				if (!isTx) {
					session.close();
				}
			}			
		}
	}


	private static List<HashMap<String, Object>> formatDatas(List<HashMap<String, Object>> datas,
			String dataSqlid) throws Exception {
				
		// 凭证查询
		if("Dynasearch_pzxx_getData".equals(dataSqlid)) {
			List<HashMap<String, Object>> list = new ArrayList<HashMap<String,Object>>();
			for(HashMap<String, Object> map : datas) {
				List<HashMap<String, Object>> pzflbResult = selectListByXml("PZCL.pzgl_pzflb_select", map);
				for(HashMap<String, Object> pzfl : pzflbResult) {
					HashMap<String, Object> resultMap = new HashMap<String, Object>();
					resultMap.put("pzrq", map.get("pzrq"));
					resultMap.put("pzh", (String)map.get("pzz") + "-" + (Long)map.get("pzh"));
					resultMap.put("zy", pzfl.get("zy"));
					resultMap.put("km", pzfl.get("kmqc"));
					resultMap.put("jfje", pzfl.get("jfje") == null ? "" : pzfl.get("jfje"));
					resultMap.put("dfje", pzfl.get("dfje") == null ? "" : pzfl.get("dfje"));
					resultMap.put("fhr", map.get("fhr"));
					resultMap.put("zdr", map.get("zdr"));
					list.add(resultMap);
				}
			}
			return list;
		}
		
		return datas;
		
	}





}
